#include "hddTimer.h"

void timerInit(void){
  TCCR2=0x05; /*prescaler=128*/
  ASSR|=_BV(AS2);
  TIMSK|=_BV(TOIE2);
  
  TCCR0=0x05; /*prescaler=1024*/
  TIMSK|=_BV(TOIE0);
}

ISR(TIMER2_OVF_vect){
  sec++;
  
  if(sec==60){
    minB++;
    sec=0;
  }
  
  if(minB==10){
    minA++;
    minB=0;
  }
  
  if(minA==6){
    hrB++;
    minA=0;
  }
  
  if(hrB==10){
    hrA++;
    hrB=0;
  }
  
  if(hrA==2 && hrB==4){
    hrA=0;
    hrB=0;
  }
  
}

ISR(TIMER0_OVF_vect){

/*
F_CPU=4MHz, Timer2 prescaler=1024 -> 3906Hz
Crank wheel teeth=12 -> 200Hz @ 1000rpm
we want 100rpm/tick/interrupt -> interrupt @ 20Hz
3906Hz/20Hz=195 -> we add 64 to the counter to get 256-64=192
*/

  TCNT0|=0xFc;

  if((sec&0x01) && (timeDiv==trigA)){
    PORTD|=_BV(7);
  }else{
    PORTD&=~_BV(7);
  }
  
  if(!(sec&0x01) && (timeDiv==trigA)){
    PORTD|=_BV(0);
  }else{
    PORTD&=~_BV(0);
  }
  
  if((sec&0x01) && (timeDiv==trigB)){
    PORTD|=_BV(6);
  }else{
    PORTD&=~_BV(6);
  }
  
  if(!(sec&0x01) && (timeDiv==trigB)){
    PORTD|=_BV(1);
  }else{
    PORTD&=~_BV(1);
  }
  
  timeDiv++;
  if(sec&0x01){
    trigA=digitA[minA];
    trigB=digitB[minB];
  }else{
    trigA=digitA[hrA];
    trigB=digitB[hrB];
  }
}
